#!/usr/bin/env python
# coding=utf-8
# Author:  vavava
# Created: 04/11/2012

if __name__ == '__main__':
    """ for file debug"""
    import sys,os
    sys.path.insert(0,os.path.join( os.getcwd(), '..' ))

__author__ = 'vavava'
__all__ = ['BaseGripper']

ORDER_BASE_REQ    = 1
ORDER_BASE_RESULT = 100

class Gripper(object):
    def __init__(self):
        self._request_processors={}
        self._result_processors={}
        self._param=None
        self._response=None
        self._result=None

    def grip(self,*param):
        self._param=param
        self.process_request(*param)
        self.process_result(*self._response)

    def add_request_handler(self,*handlers):
        for handler in handlers:
            if not hasattr(handler,"handler_order"):
                raise "Invalid handler:%d"%type(handler)
        for handler in handlers:
            if self._request_processors.get(handler.handler_order):
                self._request_processors[handler.handler_order].append(handler)
            else:
                self._request_processors[handler.handler_order]=[handler]

    def add_result_handler(self,*handlers):
        for handler in handlers:
            if not hasattr(handler,"handler_order"):
                raise "Invalid handler:%d"%type(handler)
        for handler in handlers:
            if self._result_processors.get(handler.handler_order):
                self._result_processors[handler.handler_order].append(handler)
            else:
                self._result_processors[handler.handler_order]=[handler]

    def process_request(self,*param):
        if len(self._request_processors) < 1:
            # default handler
            self.add_handler(DefaultRequestProcessor())
        for each in self._request_processors:
            for processor in self._request_processors[each]:
                processor.process_data(*param)

    def process_result(self):
        if len(self._result_processors) < 1:
            # default handler
            self.add_handler(DefaultResultProcessor())
        for each in self._result_processors:
            for processor in self._result_processors[each]:
                processor.process_data(*self.result)

    def get_data(self,url,charset=r'utf-8'):
        from vavava.httpclient import HttpClient
        client=HttpClient(log=None,debug_level=0,req_timeout=30)
        data=client.Get(url)
        return data.decode(charset)


class BaseRequestProcessor:
    handler_order = 0
    def add_parent(self, parent):
        self._parent = parent

    def request_data(self,*param):
        pass

    def __lt__(self, other):
        if not hasattr(other, "handler_order"):
            # Try to preserve the old behavior of having custom classes
            # inserted after default ones (works only for custom user
            # classes which are not aware of handler_order).
            return True
        return self.handler_order < other.handler_order

class DefaultRequestProcessor(BaseRequestProcessor):
    handler_order = ORDER_BASE_REQ
    def request_data(self,*param):
        if param:
            for each in param:
                print("[default request processor] %s"%each)

class BaseResultProcessor:
    handler_order = 0
    def add_parent(self, parent):
        self._parent = parent

    def process_data(self,*param):
        pass

    def __lt__(self, other):
        if not hasattr(other, "handler_order"):
            # Try to preserve the old behavior of having custom classes
            # inserted after default ones (works only for custom user
            # classes which are not aware of handler_order).
            return True
        return self.handler_order < other.handler_order

class DefaultResultProcessor(BaseResultProcessor):
    handler_order = ORDER_BASE_RESULT
    def process_data(self,*param):
        if param:
            for each in param:
                print("[default result processor] %s"%each)


if __name__ == "__main__":
    gripper = BaseGripper()
    processor1 = BaseResultProcessor()
    processor2 = BaseResultProcessor()
    processor3 = BaseResultProcessor()

    gripper.add_handler(processor1)
    gripper.add_handler(processor2)
    gripper.add_handler(processor3)

    gripper.grip("http://www.baidu.com",charset='ISO-8859-1')



